package com.amsp.oa.oademo.service.impl;

import com.amsp.oa.oademo.entity.LeaveAdjustment;
import com.amsp.oa.oademo.mapper.LeaveAdjustmentMapper;
import com.amsp.oa.oademo.service.LeaveAdjustmentService;
import com.amsp.oa.oademo.vo.LeaveAdjustmentVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LeaveAdjustmentServiceImpl extends ServiceImpl<LeaveAdjustmentMapper, LeaveAdjustment>
        implements LeaveAdjustmentService {

    @Override
    public IPage<LeaveAdjustment> getList(Integer page, Integer size, String month, String employeeName) {
        LambdaQueryWrapper<LeaveAdjustment> queryWrapper = new LambdaQueryWrapper<>();

        // 如果提供了月份，则按月份筛选
        if (StringUtils.hasText(month)) {
            String[] parts = month.split("-");
            if (parts.length == 2) {
                int year = Integer.parseInt(parts[0]);
                int monthValue = Integer.parseInt(parts[1]);

                LocalDateTime startOfMonth = LocalDateTime.of(year, monthValue, 1, 0, 0, 0);
                LocalDateTime endOfMonth;
                if (monthValue == 12) {
                    endOfMonth = LocalDateTime.of(year + 1, 1, 1, 0, 0, 0).minusNanos(1);
                } else {
                    endOfMonth = LocalDateTime.of(year, monthValue + 1, 1, 0, 0, 0).minusNanos(1);
                }

                queryWrapper.and(wrapper -> wrapper
                        .between(LeaveAdjustment::getWorkStartDate, startOfMonth, endOfMonth)
                        .or()
                        .between(LeaveAdjustment::getRestStartDate, startOfMonth, endOfMonth));
            }
        }

        // 如果提供了员工姓名，则按姓名筛选
        if (StringUtils.hasText(employeeName)) {
            queryWrapper.like(LeaveAdjustment::getEmployeeName, employeeName);
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(LeaveAdjustment::getCreateTime);

        return page(new Page<>(page, size), queryWrapper);
    }

    @Override
    public LeaveAdjustmentVO getDetail(Long id) {
        LeaveAdjustment entity = getById(id);
        if (entity == null) {
            return null;
        }
        return convertToVO(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(LeaveAdjustmentVO vo) {
        LeaveAdjustment entity = convertToEntity(vo);
        return saveOrUpdate(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDelete(List<Long> ids) {
        return removeByIds(ids);
    }

    /**
     * 将实体转换为VO
     */
    private LeaveAdjustmentVO convertToVO(LeaveAdjustment entity) {
        if (entity == null) {
            return null;
        }

        LeaveAdjustmentVO vo = new LeaveAdjustmentVO();
        vo.setId(entity.getId());
        vo.setEmployeeId(entity.getEmployeeId());
        vo.setEmployeeName(entity.getEmployeeName());
        vo.setGroup(entity.getGroupName());
        vo.setPosition(entity.getPosition());
        vo.setReason(entity.getReason());

        // 转换上班开始日期
        if (entity.getWorkStartDate() != null) {
            Map<String, String> workStartDate = new HashMap<>();
            workStartDate.put("year", String.valueOf(entity.getWorkStartDate().getYear()));
            workStartDate.put("month", String.valueOf(entity.getWorkStartDate().getMonthValue()));
            workStartDate.put("day", String.valueOf(entity.getWorkStartDate().getDayOfMonth()));
            workStartDate.put("hour", String.valueOf(entity.getWorkStartDate().getHour()));
            workStartDate.put("minute", String.valueOf(entity.getWorkStartDate().getMinute()));
            vo.setWorkStartDate(workStartDate);
        }

        // 转换上班结束日期
        if (entity.getWorkEndDate() != null) {
            Map<String, String> workEndDate = new HashMap<>();
            workEndDate.put("year", String.valueOf(entity.getWorkEndDate().getYear()));
            workEndDate.put("month", String.valueOf(entity.getWorkEndDate().getMonthValue()));
            workEndDate.put("day", String.valueOf(entity.getWorkEndDate().getDayOfMonth()));
            workEndDate.put("hour", String.valueOf(entity.getWorkEndDate().getHour()));
            workEndDate.put("minute", String.valueOf(entity.getWorkEndDate().getMinute()));
            vo.setWorkEndDate(workEndDate);
        }

        // 转换休息开始日期
        if (entity.getRestStartDate() != null) {
            Map<String, String> restStartDate = new HashMap<>();
            restStartDate.put("year", String.valueOf(entity.getRestStartDate().getYear()));
            restStartDate.put("month", String.valueOf(entity.getRestStartDate().getMonthValue()));
            restStartDate.put("day", String.valueOf(entity.getRestStartDate().getDayOfMonth()));
            restStartDate.put("hour", String.valueOf(entity.getRestStartDate().getHour()));
            restStartDate.put("minute", String.valueOf(entity.getRestStartDate().getMinute()));
            vo.setRestStartDate(restStartDate);
        }

        // 转换休息结束日期
        if (entity.getRestEndDate() != null) {
            Map<String, String> restEndDate = new HashMap<>();
            restEndDate.put("year", String.valueOf(entity.getRestEndDate().getYear()));
            restEndDate.put("month", String.valueOf(entity.getRestEndDate().getMonthValue()));
            restEndDate.put("day", String.valueOf(entity.getRestEndDate().getDayOfMonth()));
            restEndDate.put("hour", String.valueOf(entity.getRestEndDate().getHour()));
            restEndDate.put("minute", String.valueOf(entity.getRestEndDate().getMinute()));
            vo.setRestEndDate(restEndDate);
        }

        vo.setApplicant(entity.getApplicant());
        vo.setGroupReviewer(entity.getGroupReviewer());
        vo.setDepartmentReviewer(entity.getDepartmentReviewer());
        vo.setDirectorApprover(entity.getDirectorApprover());
        vo.setGeneralManagerApprover(entity.getGeneralManagerApprover());
        vo.setManagementDepartmentOpinion(entity.getManagementDepartmentOpinion());
        vo.setPresidentApprover(entity.getPresidentApprover());

        if (entity.getPresidentApproverDate() != null) {
            vo.setPresidentApproverDate(entity.getPresidentApproverDate().toString());
        }

        vo.setStatus(entity.getStatus());

        return vo;
    }

    /**
     * 将VO转换为实体
     */
    private LeaveAdjustment convertToEntity(LeaveAdjustmentVO vo) {
        if (vo == null) {
            return null;
        }

        LeaveAdjustment entity = new LeaveAdjustment();
        entity.setId(vo.getId());
        entity.setEmployeeId(vo.getEmployeeId());
        entity.setEmployeeName(vo.getEmployeeName());
        entity.setGroupName(vo.getGroup());
        entity.setPosition(vo.getPosition());
        entity.setReason(vo.getReason());

        // 转换上班开始日期
        if (vo.getWorkStartDate() != null && !vo.getWorkStartDate().isEmpty()) {
            try {
                int year = Integer.parseInt(vo.getWorkStartDate().get("year"));
                int month = Integer.parseInt(vo.getWorkStartDate().get("month"));
                int day = Integer.parseInt(vo.getWorkStartDate().get("day"));
                int hour = Integer.parseInt(vo.getWorkStartDate().get("hour"));
                int minute = Integer.parseInt(vo.getWorkStartDate().get("minute"));
                entity.setWorkStartDate(LocalDateTime.of(year, month, day, hour, minute));
            } catch (Exception e) {
                // 日期格式错误，忽略
            }
        }

        // 转换上班结束日期
        if (vo.getWorkEndDate() != null && !vo.getWorkEndDate().isEmpty()) {
            try {
                int year = Integer.parseInt(vo.getWorkEndDate().get("year"));
                int month = Integer.parseInt(vo.getWorkEndDate().get("month"));
                int day = Integer.parseInt(vo.getWorkEndDate().get("day"));
                int hour = Integer.parseInt(vo.getWorkEndDate().get("hour"));
                int minute = Integer.parseInt(vo.getWorkEndDate().get("minute"));
                entity.setWorkEndDate(LocalDateTime.of(year, month, day, hour, minute));
            } catch (Exception e) {
                // 日期格式错误，忽略
            }
        }

        // 转换休息开始日期
        if (vo.getRestStartDate() != null && !vo.getRestStartDate().isEmpty()) {
            try {
                int year = Integer.parseInt(vo.getRestStartDate().get("year"));
                int month = Integer.parseInt(vo.getRestStartDate().get("month"));
                int day = Integer.parseInt(vo.getRestStartDate().get("day"));
                int hour = Integer.parseInt(vo.getRestStartDate().get("hour"));
                int minute = Integer.parseInt(vo.getRestStartDate().get("minute"));
                entity.setRestStartDate(LocalDateTime.of(year, month, day, hour, minute));
            } catch (Exception e) {
                // 日期格式错误，忽略
            }
        }

        // 转换休息结束日期
        if (vo.getRestEndDate() != null && !vo.getRestEndDate().isEmpty()) {
            try {
                int year = Integer.parseInt(vo.getRestEndDate().get("year"));
                int month = Integer.parseInt(vo.getRestEndDate().get("month"));
                int day = Integer.parseInt(vo.getRestEndDate().get("day"));
                int hour = Integer.parseInt(vo.getRestEndDate().get("hour"));
                int minute = Integer.parseInt(vo.getRestEndDate().get("minute"));
                entity.setRestEndDate(LocalDateTime.of(year, month, day, hour, minute));
            } catch (Exception e) {
                // 日期格式错误，忽略
            }
        }

        entity.setApplicant(vo.getApplicant());
        entity.setGroupReviewer(vo.getGroupReviewer());
        entity.setDepartmentReviewer(vo.getDepartmentReviewer());
        entity.setDirectorApprover(vo.getDirectorApprover());
        entity.setGeneralManagerApprover(vo.getGeneralManagerApprover());
        entity.setManagementDepartmentOpinion(vo.getManagementDepartmentOpinion());
        entity.setPresidentApprover(vo.getPresidentApprover());

        if (StringUtils.hasText(vo.getPresidentApproverDate())) {
            try {
                entity.setPresidentApproverDate(LocalDate.parse(vo.getPresidentApproverDate()));
            } catch (Exception e) {
                // 日期格式错误，忽略
            }
        }

        entity.setStatus(vo.getStatus());

        return entity;
    }
}